var fs = require('fs')
var express = require("express")
var User = require('./mongojs/user.js')
var Rights = require('./mongojs/rights.js')
var Admin = require('./mongojs/admin.js')
var Posting = require('./mongojs/posting.js')
var Like = require('./mongojs/like.js')
var Require = require('./mongojs/require.js')
var CommentsLike = require('./mongojs/commentslike.js')
var router = express.Router()
var Token = require('./token.js')
const uploadImg = require('./uploadImg')

//处理用户注册请求
router.post('/register', function(req, res, next) {
    var body = req.body
    User.findOne({
                $or: [{
                        email: body.email
                    },
                    {
                        username: body.username
                    }
                ]
            }

        )
        .then(function(data) {
            if (data) {
                return res.status(200).json({
                    err_code: 1,
                    msg: "用户已被注册"
                })
            }
            new User(body).save(function(err, data) {
                if (err) {
                    return next(err)
                }
                return res.status(200).json({
                    err_code: 0,
                    msg: "ok"
                })
            })
        }, function(err) {
            return next(err) //如果next带参数，不再顺着往下找，直接找到有四个参数的应用级别的中间件
        }).catch(error => console.log(error))

})
//处理用户登录请求
router.post('/login', function(req, res, next) {
    var body = req.body
    var token = req.headers.authorization
    //第一次登陆时token为空
    if (token == 'null') {
        console.log('第一次登陆token为空')
        token = Token.createToken(body, '15d')
    }
    var verifyToken = Token.verifyToken(token)

    User.findOne({
        email: verifyToken.email,
        password: verifyToken.password

    }).then(function(data) {
        if (!data) {
            return res.status(200).json({
                err_code: 1,
                msg: "邮箱与密码匹配错误"
            })
        } else {
            res.status(200).json({
                err_code: 0,
                msg: "ok可以登陆",
                token: token
            })
        }
    }, function(err) {
        return next(err)
    }).catch(error => console.log(error))

})
//返回用户数据
router.get('/users', function(req, res, next) {
    var pageNum = parseInt(req.query.pageNum)
    var pageSize = parseInt(req.query.pageSize)
    var query = req.query.query
    var total = 0
    var levels = parseInt(req.query.levels)

    if (query != '') {
        User.find({ 'username': query }, function(err, data) {
            if (err) {
                return next(err)
            }
            return res.status(200).json({
                err_code: 0,
                msg: "查询指定用户的数据成功",
                data: data
            })
        })
    } else {
        //countDocuments()：符合查询条件的数目长度
        //estimatedDocumentCount()：忽略查询条件，返回所有数据的数目长度
        User.estimatedDocumentCount(function(err, data) {
            total = data
        })
        User.find({ 'levels': levels }).skip((pageNum - 1) * pageSize).limit(pageSize).sort({ 'create_time': 1 }).exec((err, data) => {
            if (err) {
                return next(err)
            }
            return res.status(200).json({
                err_code: 0,
                msg: "查询指定页码的数据成功",
                data: data,
                total: total
            })
        })
    }
})

//处理发帖请求
router.post('/community/posting', function(req, res, next) {
    let body = req.body
    let token = req.headers.authorization
    let verifyToken = Token.verifyToken(token)
    body.id = Math.floor(Math.random() * 10000 + 1);
    User.findOne({ email: verifyToken.email })
        .then(function(data) {
            if (!data) {
                return next()
            }
            body.username = data.username
            body.useravatar = data.Avatar
            body.introduce = data.introduce
            new Posting(body).save(function(err, data) {
                if (err) {
                    console.log(err)
                    return next(err)
                }
                res.status(200).json({
                    err_code: 0,
                    msg: "发帖成功"
                })
            })
        }, function(err) {
            return next(err)
        }).catch(error => console.log(error))
})
//处理上传图片请求
router.post('/community/posting/uploadImg', function(req, res, next) {
    uploadImg(req, res)
})
// 处理获取所有帖子请求
router.get('/community/getPostlist', function(req, res, next) {
    let pageNum = parseInt(req.query.pageNum)
    let pageSize = parseInt(req.query.pageSize)
    let total = 0
    let query = req.query.query

    if (query != '') {
        //countDocuments()：符合查询条件的数目长度
        //estimatedDocumentCount()：忽略查询条件，返回所有数据的数目长度
        Posting.estimatedDocumentCount(function(err, data) {
            total = data
        })
        Posting.find().skip((pageNum - 1) * pageSize).limit(pageSize).sort({ 'create_time': -1 }).exec((err, data) => {
            if (err) {
                return next(err)
            }
            let Array = []
            for (item of data) {
                if (item.tagArray.some((val) => val === query)) {
                    Array.push(item)
                }
            }
            console.log(Array.length)
            return res.status(200).json({
                err_code: 0,
                msg: "查询指定分区的指定页码的数据成功",
                data: Array,
                total: Array.length
            })
        })
    } else {
        Posting.estimatedDocumentCount(function(err, data) {
            total = data
        })
        Posting.find().skip((pageNum - 1) * pageSize).limit(pageSize).sort({ 'create_time': -1 }).exec((err, data) => {
            if (err) {
                return next(err)
            }
            return res.status(200).json({
                err_code: 0,
                msg: "查询全部分区的指定页码的数据成功",
                data: data,
                total: total
            })
        })
    }

})
// 处理查询帖子请求
router.get('/community/getOnePost/:id', function(req, res, next) {
    let id = req.params.id

    Posting.findOne({ 'id': id }, function(err, data) {
        if (err) {
            return next(err)
        }
        return res.status(200).json({
            err_code: 0,
            msg: "查询指定帖子的数据成功",
            data: data
        })
    })
})
// 处理点赞功能
router.get('/community/post/like', function(req, res, next) {
    let token = req.headers.authorization
    let verifyToken = Token.verifyToken(token)
    let query = req.query

    // 根据token找到 user_id
    User.findOne({ email: verifyToken.email })
        .then(function(data) {
            if (!data) {
                return next()
            }
            const user_id = data._id
            // 查看文章是否存在于Like表
            Like.findOne({ post_id: query.post_id }, function(err, data) {
                if (err) {
                    return next(err)
                }
                // 如果是文章id不存在也就是第一次被点赞则直接保存用户id和文章id
                if (!data) {
                    let user_id_Array = []
                    user_id_Array.push(user_id)
                    query.user_id_Array = user_id_Array

                    new Like(query).save(function(err, data) {
                        if (err) {
                            return next(err)
                        }
                        res.status(200).json({
                            err_code: 0,
                            msg: "文章第一次被点赞成功"
                        })
                    })
                } else {
                    let user_id_Array = data.user_id_Array
                    // 判断用户id是否存在也就是点没点赞
                    let is_user_id = user_id_Array.some(item => {
                        return item == user_id
                    })
                    if (is_user_id === false) {
                        user_id_Array.push(user_id)
                        let _id = data._id

                        // 如果是文章id存在则更新点赞的用户id
                        Like.findByIdAndUpdate(_id, { 'user_id_Array': user_id_Array }, function(err, data) {
                            if (err) {
                                return next(err)
                            }
                            return res.status(200).json({
                                err_code: 0,
                                msg: "点赞更新成功"
                            })
                        })
                    } else {
                        return res.status(200).json({
                            err_code: -1,
                            msg: "该用户已经对此文章点过赞了"
                        })
                    }

                }
            })
        }, function(err) {
            return next(err)
        }).catch(error => console.log(error))
})
// 处理用户是否对文章点过赞
router.get('/community/post/islike', function(req, res, next) {
    let token = req.headers.authorization
    let verifyToken = Token.verifyToken(token)
    let query = req.query

    // 根据token找到 user_id
    User.findOne({ email: verifyToken.email })
        .then(function(data) {
            if (!data) {
                return next()
            }
            const user_id = data._id
            // 查看文章是否存在于Like表
            Like.findOne({ post_id: query.post_id }, function(err, data) {
                if (err) {
                    return next(err)
                }
                if (!data) {
                    return res.status(200).json({
                        err_code: -2,
                        msg: "还没有人对此文章点过赞"
                    })
                }
                if (data) {
                    let user_id_Array = data.user_id_Array
                    // 判断用户id是否存在也就是点没点赞
                    let is_user_id = user_id_Array.some(item => {
                        return item == user_id
                    })
                    if (is_user_id === false) {
                        return res.status(200).json({
                            err_code: -1,
                            msg: "登陆的用户没有对此文章点赞"
                        })
                    }
                    return res.status(200).json({
                        err_code: 0,
                        msg: "该用户已经对此文章点过赞了"
                    })
                }
            })
        }, function(err) {
            return next(err)
        }).catch(error => console.log(error))
})
// 处理posting表的like数据加1
router.get('/community/post/addlike', function(req, res, next) {
    let _id = req.query._id
    Posting.findOne({ '_id': _id }, function(err, data) {
        if (err) {
            return next(err)
        }
        let like = data.like + 1
        Posting.findByIdAndUpdate(_id, { 'like': like }, function(err, data) {
            if (err) {
                return next(err)
            }
            return res.status(200).json({
                err_code: 0,
                msg: "like加1成功"
            })
        })
    })
})
// 处理用户收藏文章请求
router.get('/community/post/addCollection', function(req, res, next) {
    let post_id = req.query.post_id
    let token = req.headers.authorization
    let verifyToken = Token.verifyToken(token)

    // 根据token找到 user_id
    User.findOne({ email: verifyToken.email }, function(err, data) {
        if (err) {
            return next(err)
        }
        let collections = data.collections
        let _id = data._id
        // 判断post_id是否存在也就是用户是否已经收藏
        let is_post_id = collections.some(item => {
            return item == post_id
        })
        if (is_post_id) {
            return res.status(200).json({
                err_code: -1,
                msg: "登陆的用户已经收藏了此文章"
            })
        } else {
            collections.push(post_id)
            User.findByIdAndUpdate(_id, { 'collections': collections }, function(err, data) {
                if (err) {
                    console.log(err)
                    return next(err)
                }
                return res.status(200).json({
                    err_code: 0,
                    msg: "收藏成功"
                })
            })
        }
    })
})
// 处理用户查询收藏的文章请求
router.get('/community/user/searchCollection', function(req, res, next) {
    let token = req.headers.authorization
    let verifyToken = Token.verifyToken(token)

    User.findOne({ email: verifyToken.email }, function(err, data) {
        if (err) {
            return next(err)
        }
        let collections = data.collections
        let collectionsArray = []
        let total = 0

        for (item of collections) {
            Posting.findOne({ 'id': item }, function(err, data) {
                if (err) {
                    console.log(err)
                    return next(err)
                }
                collectionsArray.push(data)
            })

        }

        setTimeout(() => {
            return res.status(200).json({
                err_code: 0,
                msg: "查询收藏的帖子成功",
                data: collectionsArray
            })
        }, 1500)

    })
})
// 处理用户查询曾经回答的文章请求
router.get('/community/user/answerPost', function(req, res, next) {
    let token = req.headers.authorization
    let verifyToken = Token.verifyToken(token)

    User.findOne({ email: verifyToken.email }, function(err, data) {
        if (err) {
            return next(err)
        }

        let username = data.username


        Posting.find({ 'username': username }, function(err, data) {
            if (err) {
                console.log(err)
                return next(err)
            }

            return res.status(200).json({
                err_code: 0,
                msg: "查询回答的帖子成功",
                data: data
            })
        })
    })
})
// 处理用户是否收藏打开的文章
router.get('/community/post/isCollection', function(req, res, next) {
    let post_id = req.query.post_id
    let token = req.headers.authorization
    let verifyToken = Token.verifyToken(token)

    // 根据token找到 user_id
    User.findOne({ email: verifyToken.email }, function(err, data) {
        if (err) {
            return next(err)
        }
        if (data.collections !== []) {
            let collections = data.collections
            // 判断post_id是否存在也就是用户是否已经收藏
            let is_post_id = collections.some(item => {
                return item == post_id
            })
            if (is_post_id) {
                return res.status(200).json({
                    err_code: 0,
                    msg: "登陆的用户已经收藏了此文章"
                })
            }
        }

    })
})
// 处理用户取消收藏打开的文章
router.get('/community/post/deleteCollection', function(req, res, next) {
    let post_id = req.query.post_id
    let token = req.headers.authorization
    let verifyToken = Token.verifyToken(token)

    // 根据token找到 user_id
    User.findOne({ email: verifyToken.email }, function(err, data) {
        if (err) {
            return next(err)
        }
        let collections = data.collections
        let _id = data._id

        collections.remove(post_id)
        User.findByIdAndUpdate(_id, { 'collections': collections }, function(err, data) {
            if (err) {
                console.log(err)
                return next(err)
            }
            return res.status(200).json({
                err_code: 0,
                msg: "取消收藏成功"
            })
        })
    })
})
// 处理打开的文章收藏+1
router.get('/community/post/incrementCollection', function(req, res, next) {
    let _id = req.query._id
    Posting.findOne({ '_id': _id }, function(err, data) {
        if (err) {
            return next(err)
        }
        let collections = data.collections + 1
        Posting.findByIdAndUpdate(_id, { 'collections': collections }, function(err, data) {
            if (err) {
                return next(err)
            }
            return res.status(200).json({
                err_code: 0,
                msg: "collections加1成功"
            })
        })
    })
})
// 处理打开的文章收藏-1
router.get('/community/post/decrementCollection', function(req, res, next) {
    let _id = req.query._id
    Posting.findOne({ '_id': _id }, function(err, data) {
        if (err) {
            return next(err)
        }
        let collections = data.collections - 1
        Posting.findByIdAndUpdate(_id, { 'collections': collections }, function(err, data) {
            if (err) {
                return next(err)
            }
            return res.status(200).json({
                err_code: 0,
                msg: "collections-1成功"
            })
        })
    })
})
//处理评论文章
router.get('/community/postRead/discuss', function(req, res, next) {
    let token = req.headers.authorization
    let verifyToken = Token.verifyToken(token)
    let _id = req.query._id
    let content = req.query.content

    // 根据token找到 user_id
    User.findOne({ email: verifyToken.email }, function(err, data) {
        if (err) {
            return next(err)
        }
        let username = data.username
        Posting.findOne({ '_id': _id }, function(err, data) {
            if (err) {
                return next(err)
            }
            let comments = data.comments
            let postUsername = data.username

            let obj = {}
            // 如果评论的人是发表文章的人
            if (postUsername == username) {
                obj.isOriginalPoster = true
            }
            obj.username = username
            obj.content = content
            obj.id = Math.floor(Math.random() * 200000 + 100000);
            comments.push(obj)

            Posting.findByIdAndUpdate(_id, { 'comments': comments }, function(err, data) {
                if (err) {
                    return next(err)
                }
                return res.status(200).json({
                    err_code: 0,
                    msg: "存储一级评论成功",
                    data: data
                })
            })
        })
    })
})
//处理获取打开文章的所有评论
router.get('/community/postRead/getAllDiscuss', function(req, res, next) {
    let _id = req.query._id

    Posting.findOne({ '_id': _id }, function(err, data) {
        if (err) {
            return next(err)
        }
        return res.status(200).json({
            err_code: 0,
            msg: "获取打开文章所有的评论成功",
            data: data.comments
        })
    })
})
//处理回复一级评论
router.get('/community/postRead/replyDiscuss', function(req, res, next) {
    let token = req.headers.authorization
    let verifyToken = Token.verifyToken(token)
    let _id = req.query._id
    let content = req.query.content
    let replyUsername = req.query.replyUsername

    // 根据token找到 user_name
    User.findOne({ email: verifyToken.email }, function(err, data) {
        if (err) {
            return next(err)
        }
        let username = data.username
        Posting.findOne({ '_id': _id }, function(err, data) {
            if (err) {
                return next(err)
            }
            let comments = data.comments
            let postUsername = data.username

            for (item of comments) {
                //如果回复的是一级评论
                if (item.username == replyUsername) {
                    let obj = {}
                    let children = item.children
                    // 如果评论的人是发表文章的人
                    if (postUsername == username) {
                        obj.isOriginalPoster = true
                    }
                    obj.username = username
                    obj.content = content
                    obj.id = Math.floor(Math.random() * 100000 + 10000)
                    children.push(obj)
                    console.log(comments)
                }
            }
            Posting.findByIdAndUpdate(_id, { 'comments': comments }, function(err, data) {
                if (err) {
                    return next(err)
                }
                return res.status(200).json({
                    err_code: 0,
                    msg: "回复一级评论成功",
                    data: data
                })
            })

        })
    })
})
//处理回复二级评论
router.get('/community/postRead/replySecondDiscuss', function(req, res, next) {
    let token = req.headers.authorization
    let verifyToken = Token.verifyToken(token)
    let _id = req.query._id
    let content = req.query.content
    let replyUsername = req.query.replyUsername
    let FirstUsername = req.query.FirstUsername

    // 根据token找到 user_name
    User.findOne({ email: verifyToken.email }, function(err, data) {
        if (err) {
            return next(err)
        }
        let username = data.username
        Posting.findOne({ '_id': _id }, function(err, data) {
            if (err) {
                return next(err)
            }
            let comments = data.comments
            let postUsername = data.username

            for (item of comments) {
                if (item.username == FirstUsername) {
                    let obj = {}
                    // 如果回复评论的人是发表文章的人
                    if (postUsername == username) {
                        obj.isOriginalPoster = true
                    }
                    obj.username = username
                    obj.content = content
                    obj.showReplyText = true
                    obj.replyUsername = replyUsername
                    obj.id = Math.floor(Math.random() * 100000 + 10000)
                    let children = item.children
                    children.push(obj)
                }
            }
            Posting.findByIdAndUpdate(_id, { 'comments': comments }, function(err, data) {
                if (err) {
                    return next(err)
                }
                return res.status(200).json({
                    err_code: 0,
                    msg: "回复二级评论成功",
                    data: data
                })
            })

        })
    })
})
// 处理posting表的评论字段的like数据加1
router.get('/community/post/AddDiscussLike', function(req, res, next) {
    let _id = req.query._id
    let commentsId = req.query.commentsId
    Posting.findOne({ '_id': _id }, function(err, data) {
        if (err) {
            return next(err)
        }
        let comments = data.comments

        for (item of comments) {
            if (item.id == commentsId) {
                item.like += 1
            }
        }
        Posting.findByIdAndUpdate(_id, { 'comments': comments }, function(err, data) {
            if (err) {
                return next(err)
            }
            return res.status(200).json({
                err_code: 0,
                msg: "comments的like加1成功"
            })
        })
    })
})
// 处理评论点赞功能
router.get('/community/post/CommentsLike', function(req, res, next) {
    let token = req.headers.authorization
    let verifyToken = Token.verifyToken(token)
    let query = req.query

    // 根据token找到 user_id
    User.findOne({ email: verifyToken.email }, function(err, data) {
        if (!data) {
            return next(err)
        }
        const user_id = data._id
        // 查看文章是否存在于Like表
        CommentsLike.findOne({ commentsId: query.commentsId }, function(err, data) {
            if (err) {
                return next(err)
            }
            // 如果是评论id不存在也就是第一次被点赞则直接保存用户id和评论id
            if (!data) {
                let user_id_Array = []
                user_id_Array.push(user_id)
                query.user_id_Array = user_id_Array

                new CommentsLike(query).save(function(err, data) {
                    if (err) {
                        return next(err)
                    }
                    res.status(200).json({
                        err_code: 0,
                        msg: "评论第一次被点赞成功"
                    })
                })
            } else {
                let user_id_Array = data.user_id_Array
                // 判断用户id是否存在也就是点没点赞
                let is_user_id = user_id_Array.some(item => {
                    return item == user_id
                })
                if (is_user_id === false) {
                    user_id_Array.push(user_id)
                    let _id = data._id

                    // 如果是文章id存在则更新点赞的用户id
                    CommentsLike.findByIdAndUpdate(_id, { 'user_id_Array': user_id_Array }, function(err, data) {
                        if (err) {
                            return next(err)
                        }
                        return res.status(200).json({
                            err_code: 0,
                            msg: "评论点赞更新成功"
                        })
                    })
                } else {
                    return res.status(200).json({
                        err_code: -1,
                        msg: "该用户已经对此评论点过赞了"
                    })
                }

            }
        })
    })
})

// 反馈留言
router.post('/community/require', function(req, res, next) {
    let body = req.body
    let content = body.content
    let id = Math.floor(Math.random() * 10000 + 1)
    body.id = id
    body.reqContent = content
    body.create_time = Date.now()

    new Require(body).save(function(err, data) {
        if (err) {
            console.log(err)
            return next(err)
        }
        res.status(200).json({
            err_code: 0,
            msg: "反馈成功"
        })
    })

})
// 获取反馈留言
router.get('/community/getrequire', function(req, res, next) {
    let pageNum = parseInt(req.query.pageNum)
    let pageSize = parseInt(req.query.pageSize)
    let total = 0

    Require.find(function(err, data) {
        if (err) {
            return next(err)
        }
        Require.estimatedDocumentCount(function(err, totaldata) {
            total = data
            return res.status(200).json({
                err_code: 0,
                msg: "获取所有的反馈成功",
                data: data,
                total: totaldata
            })
        })

    }).skip((pageNum - 1) * pageSize).limit(pageSize).sort({ 'create_time': -1 })
})
//处理修改用户信息请求
router.post('/user/update', function(req, res, next) {
    let introduce = req.body.introduce
    let username = req.body.username
    
    let token = req.headers.authorization
    let verifyToken = Token.verifyToken(token)

    // 根据token找到 user_id
    User.findOne({ email: verifyToken.email }, function(err, data) {
        if (err) {
            return next(err)
        }
        let _id = data._id
        User.findByIdAndUpdate(_id, { 'introduce': introduce, 'username': username }, function(err, data) {
            if (err) {
                return next(err)
            }
            return res.status(200).json({
                err_code: 0,
                msg: "指定用户的信息修改成功"
            })
        })
    })

})
//处理修改用户头像请求
router.put('/user/updateAvatar', function(req, res, next) {  
    let token = req.headers.authorization
    let verifyToken = Token.verifyToken(token)
    let updateAvatarImgUrl = req.body.updateAvatarImgUrl
    // 根据token找到 user_id
    User.findOne({ email: verifyToken.email }, function(err, data) {
        if (err) {
            return next(err)
        }
        let _id = data._id
        User.findByIdAndUpdate(_id, { 'Avatar': updateAvatarImgUrl }, function(err, data) {
            if (err) {
                return next(err)
            }
            return res.status(200).json({
                err_code: 0,
                msg: "指定用户的头像修改成功",
                AvatarUrl:data.Avatar
            })
        })
    })

})
// 查询个人信息
router.get('/user/getUserMessage', function(req, res, next) {
    let token = req.headers.authorization
    let verifyToken = Token.verifyToken(token)

    // 根据token找到 user_id
    User.findOne({ email: verifyToken.email }, function(err, data) {
        if (err) {
            return next(err)
        }

        return res.status(200).json({
            err_code: 0,
            msg: "获取信息成功",
            data: data
        })

    })

})
module.exports = router